package com.coocaa.app.gamecenter.pages.arsenal.view;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.coocaa.app.gamecenter.pages.arsenal.data.ArsenalData;
import com.coocaa.app.gamecenter.pages.arsenal.data.WeaponData;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.tianci.appstore.R;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xfk on 2015/11/5.
 */
public class ArsenalGridView extends FrameLayout implements ItemListView.SlideUpAndDownListener, ArsenalScrollView.OnScrollEndListener {
    private static String tag = "arsenal";
    private Context mContext;
    private LinearLayout linearLayout;
    private ImageView hasMoreArsenalImag;
    private ArsenalScrollView mScrollView;
    private List<WeaponData> weaponDataList;
    private int mScrollViewY = -1;
    private int currentItemIndex = 0;
    private int currentArsenalItemId = 0;
    private int currentKeyCode = 0;
    private int currentPosition = 0;
    private Animation mAlphaAnimation;
    private boolean isTurnPage = false;
    private ItemFocusView itemFocusView;
    private List<ArsenalItemView> arsenalItemViewList = new ArrayList<ArsenalItemView>();
    private ItemListView.ItemEventChangeInterface itemEventChangeInterface;
    public ArsenalGridView(Context context) {
        super(context);
        mContext = context;

        createLayout();
    }

    public void refreshUI(ArsenalData arsenalData) {
        if(arsenalData  == null || arsenalData.weaponDataList == null)
            return;

        int[] locations = new int[2];
        mScrollView.getLocationOnScreen(locations);
        mScrollViewY = locations[1];
        weaponDataList = arsenalData.weaponDataList;
        int id = 0;
        for(WeaponData weaponData: arsenalData.weaponDataList) {
            createArsenalItemView(id, weaponData);
            if(arsenalItemViewList.size() == 3)
                break;
            id++;
        }

        if(weaponDataList.size() > 2) {
            hasMoreArsenalImag.setVisibility(VISIBLE);
            hasMoreArsenalImag.startAnimation(mAlphaAnimation);
            currentItemIndex = 1;
        }

        LogUtils.i(tag, "requestItemFocus 0");

        if(linearLayout.getChildCount() > 0 && linearLayout.getChildAt(0) instanceof ArsenalItemView) {
            View view = ((ArsenalItemView) linearLayout.getChildAt(0)).getItemView(0);
            ((ArsenalItemView) linearLayout.getChildAt(0)).requestItemFocus(0);
        }
    }

    private void createArsenalItemView(int id, WeaponData weaponData) {
        ArsenalItemView arsenalItemView = new ArsenalItemView(mContext);
        arsenalItemView.setId(id);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                CoocaaApplication.Div(463));
        linearLayout.addView(arsenalItemView, params);
        arsenalItemView.setFocusChangedEvent(itemFocusView.focusChangedEvent);
        arsenalItemView.setData(weaponData);
        arsenalItemView.setItemEventChangeInterface(itemEventChangeInterface);
        arsenalItemView.setSlideUpAndDownListener(this);
        arsenalItemViewList.add(arsenalItemView);
    }

    private void createLayout() {

        itemFocusView = new ItemFocusView(mContext, R.drawable.arsenal_item_selector);
        this.addView(itemFocusView);

        mScrollView = new ArsenalScrollView(mContext);
        mScrollView.setmOnScrollEndListener(this);
        mScrollView.setOverScrollMode(OVER_SCROLL_NEVER);
        LayoutParams scrollViewParams = new LayoutParams(LayoutParams.MATCH_PARENT, CoocaaApplication.Div(463) * 2);
        scrollViewParams.topMargin = 0;
        this.addView(mScrollView, scrollViewParams);
        setThumbV(R.drawable.game_center_progress_bar_100, mScrollView);

        linearLayout = new LinearLayout(mContext);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        LayoutParams linearParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        mScrollView.addView(linearLayout, linearParams);

        hasMoreArsenalImag = new ImageView(mContext);
        LayoutParams imgParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        imgParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
        imgParams.bottomMargin = 0;
        hasMoreArsenalImag.setImageResource(R.drawable.arsenal_arrows);
        hasMoreArsenalImag.setVisibility(INVISIBLE);
        this.addView(hasMoreArsenalImag, imgParams);

        mAlphaAnimation = new AlphaAnimation(0f, 1.0f);
        mAlphaAnimation.setRepeatCount(-1);
        mAlphaAnimation.setRepeatMode(Animation.REVERSE);
        mAlphaAnimation.setDuration(800);
    }

    private void smoothScroll(int x, int y) {
        if(mScrollView != null) {
            mScrollView.smoothScroll(x, y);
        }
    }

    public void setItemEventChangeInterface(ItemListView.ItemEventChangeInterface changeInterface) {
        itemEventChangeInterface = changeInterface;
    }

    public void setThumbV(int id, ScrollView v) {
        try {
            Field mScrollCacheField = View.class.getDeclaredField("mScrollCache");
            mScrollCacheField.setAccessible(true);
            Object mScrollCache = mScrollCacheField.get(v); // scr is your Scroll View

            Field scrollBarField = mScrollCache.getClass().getDeclaredField("scrollBar");
            scrollBarField.setAccessible(true);
            Object scrollBar = scrollBarField.get(mScrollCache);

            Method method = scrollBar.getClass().getDeclaredMethod("setVerticalThumbDrawable",
                    Drawable.class);
            method.setAccessible(true);
            // Set your drawable here.
            method.invoke(scrollBar, getResources().getDrawable(id));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onDestroy() {
        if(mScrollView != null) {
            mScrollView.removeAllViews();
            mScrollView.destroyDrawingCache();
            mScrollView = null;
        }
        if(linearLayout != null) {
            linearLayout.destroyDrawingCache();
            linearLayout.removeAllViews();
            linearLayout = null;
        }

        if(arsenalItemViewList != null) {
            for(ArsenalItemView arsenalItemView: arsenalItemViewList) {
                if(arsenalItemView != null)
                    arsenalItemView.onDestroy();

                arsenalItemView.destroyDrawingCache();
            }

            arsenalItemViewList.clear();
            arsenalItemViewList = null;
        }

        if(mAlphaAnimation != null) {
            mAlphaAnimation.cancel();
            mAlphaAnimation = null;
        }

        if(weaponDataList != null) {
            weaponDataList.clear();
            weaponDataList = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean slideUpAndDown(int arsenalItemId, int position, int keyCode) {

        if(isTurnPage)
            return true;
        int[] itemLocations = new int[2];
        currentArsenalItemId = arsenalItemId;
        currentKeyCode = keyCode;
        currentPosition = position;
        if(mScrollViewY <= 0) {
            int[] locations = new int[2];
            mScrollView.getLocationOnScreen(locations);
            mScrollViewY = locations[1];
        }
        LogUtils.i(tag, "slideUpAndDown pos:  "+position+", keyCode: "+keyCode+", arsenalItemId: "+arsenalItemId);
        arsenalItemViewList.get(arsenalItemId).getLocationOnScreen(itemLocations);
        if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
            if(itemLocations[1] == mScrollViewY) {
                if(arsenalItemViewList.size() > arsenalItemId + 1) {
                    arsenalItemViewList.get(arsenalItemId + 1).requestItemFocus(0);
                }
            } else if(itemLocations[1] > mScrollViewY) {
                if(arsenalItemViewList.size() > arsenalItemId + 1) {
                    smoothScroll(0, (int) mScrollView.getScrollY() + CoocaaApplication.Div(463));
                    arsenalItemViewList.get(arsenalItemId + 1).requestItemFocus(0);
                    currentItemIndex++;
                }
            }

            return true;
        } else if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
            if(itemLocations[1] == mScrollViewY) {
                if(arsenalItemId > 0) {
                    smoothScroll(0, (int) mScrollView.getScrollY() - CoocaaApplication.Div(463));
                    currentItemIndex --;
                    arsenalItemViewList.get(arsenalItemId - 1).requestItemFocus(0);
                }
            } else if(itemLocations[1] > mScrollViewY && arsenalItemId > 0) {
                    arsenalItemViewList.get(arsenalItemId - 1).requestItemFocus(0);
            }

            return true;
        } else if(keyCode == KeyEvent.KEYCODE_DPAD_UP) {
            int scrollY;
            //防止由于不同分辨率计算误差导致的计算错误
            LogUtils.i(tag, "up itemLocations[1]: "+itemLocations[1]+", mScrollViewY: "+mScrollViewY
            +", mScrollViewY + CoocaaApplication.Div(463): "+(mScrollViewY + CoocaaApplication.Div(463)));
            if(itemLocations[1] == mScrollViewY) {
                if(arsenalItemId > 0) {
                    arsenalItemViewList.get(currentArsenalItemId).setItemViewFocusable(false);
                    scrollY = CoocaaApplication.Div(463) * (arsenalItemId-1);
                    smoothScroll(0, scrollY);
                    currentItemIndex--;
                    isTurnPage = true;
                    hasMoreArsenalImag.setAlpha(1.0f);
                    hasMoreArsenalImag.setVisibility(VISIBLE);
                    hasMoreArsenalImag.startAnimation(mAlphaAnimation);
                }
            } else if(itemLocations[1] == mScrollViewY + CoocaaApplication.Div(463) && arsenalItemId > 0) {
                scrollY = CoocaaApplication.Div(463) * (arsenalItemId-1);
                smoothScroll(0, scrollY);
                arsenalItemViewList.get(arsenalItemId - 1).requestItemFocusByPos(position);
            } else {
                return false;
            }

            return true;
        } else if(keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
            LogUtils.i(tag, "down mScrollViewY: " + mScrollViewY + ", itemLocations[1] : "
                    + itemLocations[1]+", mScrollViewY + CoocaaApplication.Div(463): "+(mScrollViewY + CoocaaApplication.Div(463)));
            int scrollY;
            if(itemLocations[1] == mScrollViewY) {
                if(arsenalItemViewList.size() > arsenalItemId + 1) {
                    scrollY = CoocaaApplication.Div(463) * (arsenalItemId);
                    smoothScroll(0, scrollY);
                    arsenalItemViewList.get(arsenalItemId + 1).requestItemFocusByPos(position);
                }
            } else if(itemLocations[1] == mScrollViewY + CoocaaApplication.Div(463)) {
                if(arsenalItemViewList.size() < weaponDataList.size()) {
                    LogUtils.i(tag, "add new arenalItem");
                    createArsenalItemView(arsenalItemViewList.size(), weaponDataList.get(arsenalItemViewList.size()));
                }

                if(arsenalItemViewList.size() > arsenalItemId + 1) {
                    currentItemIndex++;
                    LogUtils.i(tag, "down y: "+(int) mScrollView.getScrollY());

                    arsenalItemViewList.get(currentArsenalItemId).setItemViewFocusable(false);
                    scrollY = CoocaaApplication.Div(463) * (arsenalItemId);
                    smoothScroll(0, scrollY);
                    isTurnPage = true;

                    if(arsenalItemId + 1 == arsenalItemViewList.size() -1 ) {
                        mAlphaAnimation.cancel();
                        hasMoreArsenalImag.setAlpha(0f);
                        hasMoreArsenalImag.setVisibility(INVISIBLE);
                    }
                }
            } else {
                return false;
            }

            return true;
        }

        return false;
    }

    @Override
    public void setScrollEnd(int y) {
        LogUtils.i(tag, "setScrollEnd: "+y);

        if(isTurnPage) {
            isTurnPage = false;
            if(currentKeyCode == KeyEvent.KEYCODE_DPAD_UP) {
                arsenalItemViewList.get(currentArsenalItemId - 1).requestItemFocusByPos(currentPosition);
            } else if(currentKeyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                arsenalItemViewList.get(currentArsenalItemId + 1).requestItemFocusByPos(currentPosition);
            }
        }
    }
}
